package com.commonmail.utils;




import com.commonmail.config.MailConfig;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Properties;

@Component
public class MailUtils {
    @Resource
    private MailConfig mailConfig;

    /**
     * 邮箱发送方法
     *
     * @param to      收信人
     * @param title   邮箱标题
     * @param content 邮箱内容
     */
    public boolean sendMail(String to, String title, String content) {
        try {
            
            
            
            
            
            
            //邮箱消息对象
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(mailConfig.getUsername());//发送人
            simpleMailMessage.setTo(to);//收件人
            simpleMailMessage.setSubject(title);//邮箱标题
            simpleMailMessage.setText(content);//邮箱内容

            //邮箱发送对象
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setUsername(mailConfig.getUsername());
            javaMailSender.setHost(mailConfig.getHost());
            javaMailSender.setPassword(mailConfig.getPassword());
            javaMailSender.setDefaultEncoding(mailConfig.getDefaultEncoding());

            Properties properties = new Properties();
            properties.setProperty("mail.smtp.auth", mailConfig.getSmtpAuth());
            properties.setProperty("mail.smtp.starttls.enable", mailConfig.getSmtpStarttlsEnable());
            properties.setProperty("mail.smtp.starttls.required", mailConfig.getSmtpStarttlsRequired());
            javaMailSender.setJavaMailProperties(properties);

            //实现发送邮箱
            javaMailSender.send(simpleMailMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

